#!/bin/bash
# 进程监控脚本
# 监控MediaMTX和video_recorder进程，如果不存在就启动

# 配置
LOG_FILE="/var/log/monitor.log"
CHECK_INTERVAL=3

# 进程路径
MEDIAMTX="/usr/bin/mediamtx"
VIDEO_RECORDER="/usr/bin/video_recorder"
WORK_DIR="/usr/bin"

# 日志函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# 检查进程
check_process() {
    local name="$1"
    pgrep -f "$name" > /dev/null
}

# 检查WiFi连接状态
check_wifi_connection() {
    # 检查wlan0网卡是否有活跃的WiFi连接
    nmcli -t -f DEVICE,TYPE,STATE device | grep -q "wlan0:wifi:connected"
    return $?
}

# 启动WiFi热点
start_wifi_hotspot() {
    log "📡 正在启动WiFi热点..."
    nmcli device wifi hotspot ssid zero3 password 12345678
    if [ $? -eq 0 ]; then
        log "✅ WiFi热点启动成功"
        return 0
    else
        log "❌ WiFi热点启动失败"
        return 1
    fi
}

# 启动MediaMTX
start_mediamtx() {
    if [ -f "$MEDIAMTX" ]; then
        cd "$WORK_DIR"
        nohup "$MEDIAMTX" > /dev/null 2>&1 &
        sleep 2
        if check_process "mediamtx"; then
            log "✅ MediaMTX启动成功"
            return 0
        fi
    fi
    log "❌ MediaMTX启动失败"
    return 1
}

# 启动video_recorder
start_video_recorder() {
    if [ -f "$VIDEO_RECORDER" ]; then
        cd "$WORK_DIR"
        export PYTHONUNBUFFERED=1
        nohup "$VIDEO_RECORDER" > /dev/null 2>&1 &
        sleep 2
        if check_process "video_recorder"; then
            log "✅ video_recorder启动成功"
            return 0
        fi
    fi
    log "❌ video_recorder启动失败"
    return 1
}

# 停止进程
stop_process() {
    local name="$1"
    local pids=$(pgrep -f "$name")
    if [ -n "$pids" ]; then
        for pid in $pids; do
            kill $pid 2>/dev/null
        done
        log "✅ $name 已停止"
    fi
}

# 清理函数
cleanup() {
    log "正在停止监控..."
    stop_process "mediamtx"
    stop_process "video_recorder"
    exit 0
}

# 设置信号处理
trap cleanup SIGINT SIGTERM

# 主循环
main() {
    log "🚀 进程监控器启动"
    
    # 启动WiFi热点
    log "📡 正在启动WiFi热点..."
    nmcli device wifi hotspot ssid zero3 password 12345678
    if [ $? -eq 0 ]; then
        log "✅ WiFi热点启动成功"
    else
        log "❌ WiFi热点启动失败"
    fi
    
    while true; do
        # 检查WiFi连接
        if ! check_wifi_connection; then
            log "⚠️ wlan0网卡未检测到WiFi连接，正在启动WiFi热点..."
            start_wifi_hotspot
        fi
        
        # 检查MediaMTX
        if ! check_process "mediamtx"; then
            log "⚠️ MediaMTX未运行，正在启动..."
            start_mediamtx
        fi
        
        # 检查video_recorder
        if ! check_process "video_recorder"; then
            log "⚠️ video_recorder未运行，正在启动..."
            start_video_recorder
        fi
        
        sleep $CHECK_INTERVAL
    done
}

# 运行
main 